<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * Authenticates DMUser objects against CONTENTdm(R) and sets the necessary
 * cookie which authorizes them in the CONTENTdm(R) system.
 *
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class DMCdmAuthenticationService extends DMAbstractAuthenticationService
implements DMAuthenticationService {

	private $cookie_value;

	/**
	 * @param DMUser user
	 * @param string password
	 * @return boolean True for successful authentication, false for not
	 */
	function authenticate(DMUser $user, $password) {
		// issue an HTTP request for start.exe on the cdm server using curl
		$uri = rtrim(DMHTTPRequest::getCurrent()->getURI()->getAbsoluteHostURI(), "/")
				. "/" . trim(DMConfigIni::getInstance()->getString(
						"contentdm.start_exe.path"), "/");
		$uri = new DMURI($uri);
		$req = new DMHTTPRequest($uri);
		$req->setUsername($user->getUsername());
		$req->setPassword($password);
		$client = new DMHTTPClient($req);
		$response = $client->send();

		// authentication successful; set the cdm cookie
		$cookie = $response->getCookie("DMID");
		if ($cookie) {
			$this->cookie_value = $cookie;
			return true;
		}
		// authentication failed
		return false;
	}

	/**
	 * @Override
	 * @param DMUser user
	 * @return void
	 */
	public function logout(DMUser $user) {
		parent::logout($user);
		// explicit domain is required when setting cookies on localhost
		$domain = ($_SERVER['HTTP_HOST'] != 'localhost')
			? $_SERVER['HTTP_HOST'] : false;
		setrawcookie("DMID", false, time() - 100000, "/", $domain);
	}

	public function sendCookies() {
		// explicit domain is required when setting cookies on localhost
		$domain = ($_SERVER['HTTP_HOST'] != 'localhost')
			? $_SERVER['HTTP_HOST'] : false;
		setrawcookie("DMID", $this->cookie_value, 0, "/", $domain);
	}

}
